<?php

namespace mpend\modules\passport\models;

use Yii;
use common\base\Model;
use mpend\models\User;

/**
 * 短信验证码校验模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CaptchaValidateForm extends Model {

    /**
     * 安全验证过期时间
     */
    const SECURITY_EXPIRE_TIME = 7200;

    /**
     * @var string 待校验的验证码
     */
    public $code;

    /**
     * @var string 操作内容
     */
    public $operate;

    /**
     * @var string 验证码应用范围
     */
    public $scope = SecuritySmsForm::SCOPE_ACCOUNT;

    /**
     * @var integer 登录用户ID
     */
    public $user_id;

    /**
     * @var User 登录用户
     */
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['code'], 'required'],
            ['scope', 'in', 'range' => SecuritySmsForm::getAttributeMark('scope'), 'message' => '{attribute}不在允许的范围内'],
            ['operate', 'string'],
            ['user_id', 'validateUser'],
        ];
    }

    /**
     * 校验用户是否登录
     * @param string $attribute the attribute currently being validated
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = $this->getUser();
        if (!$user) {
            $this->addError($attribute, '账号信息校验失败');
        }
    }

    /**
     * 获取用户信息
     * @return UserMeta|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findOne($this->user_id);
        }
        return $this->_user;
    }

    /**
     * 校验短信验证码是否正确
     * @return bool whether the code was validated
     */
    public function check() {
        if (!$this->validate()) {
            return $this->dumpError('校验失败');
        }
        $user = $this->getUser();
        if (!$user) {
            return false;
        }
        $mobile = $user->decryptMobile(false);
        $cache = $this->getCommonCache();
        $captcha = $cache->get('captcha_' . $this->scope . '_' . $mobile);
        if ($captcha === false || $captcha !== $this->code) {
            return $this->dumpError('输入短信验证码不正确');
        }
        if ($this->scope === SecuritySmsForm::SCOPE_RESET) {
            $user->generatePasswordResetToken();
            if ($user->save()) {
                $cache->delete('captcha_' . $this->scope . '_' . $mobile);
                return $user->password_reset_token;
            } else {
                return $user->dumpError();
            }
        } else {
            $cache->set('Security_' . $this->operate . '_' . $this->user_id, true, static::SECURITY_EXPIRE_TIME);
            $cache->delete('captcha_' . $this->scope . '_' . $mobile);
        }
        return true;
    }

}
